package com.server.orm;

import com.server.game.TransactionManager;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.server.util.LogUtil;

/**
 * 事务
 */
public abstract class OrmTransaction {

    public OrmTransaction() {
        //do nothing
    }

    /**
     * 同步
     * 执行逻辑方法。限定不可被重写
     */
    public final boolean execute() {
        Session session = HibernateManager.getSession();
        Transaction ta = null;
        try {
            ta = session.beginTransaction();//开始事务
            boolean result = action();
            if (!result) {
                return false;
            }
            ta.commit();//commit时会自动flush  保持与数据库数据的同步
        } catch (Exception e) {
            LogUtil.game.error("Exception", e);
            if (ta != null) {
                ta.rollback();
            }
            return false;
        } finally {
            session.close();
        }
        return true;
    }

    /**
     * 异步
     * 执行逻辑方法。限定不可被重写
     */
    public final boolean asyncExecute() {
        TransactionManager.getInstance().asyncAddOrmTransaction(this);
        return true;
    }

    public abstract boolean action();
}
